package com.imooc.xml.dom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class DomReadXml {

    private static final Logger L = LoggerFactory.getLogger(DomReadXml.class);

    public static void main(String[] args) {
        String filepath = "E:\\workspace\\java\\project1\\demo-xml\\src\\main\\resources\\books.xml";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        File file = new File(filepath);
        if (!file.exists() || !file.isFile()) {
            L.warn("文件：{} 不存在！", file.getAbsolutePath());
            return;
        }
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(file);
            //获取所有的book节点
            NodeList bookList = document.getElementsByTagName("book");
            L.debug("一共有{}本书", bookList.getLength());
            for (int i = 0; i < bookList.getLength(); i++) {
                L.debug("======================遍历第{}本书信息======================", i + 1);
                //获取每一个book节点
                Node book = bookList.item(i);
                //获取book节点的属性
                NamedNodeMap attrs = book.getAttributes();
                L.debug("第{}本书，共有{}个属性", i + 1, attrs.getLength());
                // 循环获取属性名及属性值，这样的好处是不受范围的限制，可任意定义
                for (int j = 0; j < attrs.getLength(); j++) {
                    Node attr = attrs.item(j);
                    L.debug("属性名：{}，属性值：{}", attr.getNodeName(), attr.getNodeValue());

                }

                // 通过Element获得节点的属性，只是属性名必须是一个预先定义好的范围，
                // 如果xml文件出现未定义的属性名将不能获取

                //Element element = (Element) bookList.item(i);
                //L.debug("id属性值：{}", element.getAttribute("id"));
                //L.debug("key属性值：{}", element.getAttribute("key"));

            }

        } catch (ParserConfigurationException e) {
            L.error("创建DocumentBuilder对象出错！", e);
        } catch (SAXException e) {
            L.error("处理Xml文件出错！", e);
        } catch (IOException e) {
            L.error("读取文件：{}出错！", filepath, e);
        }

    }

}
